import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import "./assets/css/custom.css";
import App from "./App";
import router from "./router";
import store from "./store";
// import sdk from './vendor/NIM_Web_NIM_v5.9.1'

process.env.NODE_ENV === "development" ? (global.HOSTURL = "http://127.0.0.1:8000/api") : (global.HOSTURL = "https://api.bestwepet.com/api");

axios.defaults.baseURL = global.HOSTURL;

Vue.use(VueAxios, axios);
Vue.use(ElementUI);

router.beforeEach((to, from, next) => {
  let doctorInfo = JSON.parse(sessionStorage.getItem("doctorInfo"));  
  let token = sessionStorage.getItem("token");
  if (doctorInfo) {
    store.dispatch("logined", token);
    store.dispatch("config");
    }

  let auth = store.state.auth;

  if (!auth && to.path != "/login") {
    return next({ name: "Login" });
  }

  next();
});

new Vue({
  el: "#app",
  router,
  store,
  created() {          
    axios.interceptors.response.use(
      response => {
        let token = response.headers.authorization;
        if (token) {
          store.dispatch("refreshToken", token);
        }
        return response;
      },
      error => {
        switch (error.response.status) {
          case 401:
            this.$message({
              message: "登陆超时，请重新登陆!",
              type: "error"
            });
            store.dispatch("logout");
            router.push({ name: "Login" });
            break;
          default:
            this.$message({
              message: error.response.data.msg,
              type: "error"
            });
            break;
        }
        return Promise.reject(error);
      }
    );

    
      //该方法用来全局弹窗是否离开页面
      // window.onbeforeunload = function() {      
      // var message = 'Are you sure you want to leave?';
      // return message;
      // }

  },
  components: { App },  
  template: "<App/>"
});
